package com.audaque.springboot.foshanupload.web.springsecuritycas.manager;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author zgb
 * @desc 访问决策管理器：鉴权处理器
 * @date 2022-08-05 18:08:03
 */
@Component
public class MyAccessDecisionManager implements AccessDecisionManager {
    // 用户的权限在 authentication里
    // 资源需要的权限在 collection 中：基于MyFilterInvocationSecurityMetadataSource提供的角色
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute : collection) {
            String needRole = configAttribute.getAttribute();
            //匿名访问鉴别
            if ("ROLE_ANONYMOUS".equals(needRole)) {
                //放行：可访问匿名资源
                return;
            }
            //权限鉴别：包括角色名称和后端权限表达式
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needRole)) {
                    //放行
                    return;
                }else{
                    throw new AccessDeniedException("用户权限不足");
                }

            }
        }

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}

